package classes.io;

import org.junit.Test;

import java.io.*;

/**
 * 对象流，保存对象属性
 */
public class ObjectStreamTest {
    /**
     * 保存对象属性
     */
    @Test
    public void test() {
        Person person = new Person();
        person.changeValue();//修改对象的值
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream("./src/classes/io/ObjectOutputStream.dat"));
            objectOutputStream.writeObject(person);
            objectOutputStream.flush();  // 每加一个要刷新一次
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读入对象属性
     * 事实证明，除了static、transitive的不能保存，其他的无论权限都能保存
     */
    @Test
    public void test2() {
        Person person = null;
        ObjectInputStream objectInputStream = null;
        try {
            objectInputStream = new ObjectInputStream(new FileInputStream("./src/classes/io/ObjectOutputStream.dat"));
            person = (Person) objectInputStream.readObject();
            System.out.println(person);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


class Person implements Serializable {
    private static final long serialVersionUID = 413841384713894L;

    public int publicFiled;
    private double privateFiled;
    long defaultFiled;
    protected String protectedFiled;
    public static int staticFiled;
    public transient int transitiveFiled;

    public Person() {
    }

    public void changeValue() {
        publicFiled = 100;
        privateFiled = 101.102;
        defaultFiled = 4147819344314L;
        protectedFiled = "hello";
        staticFiled = 1000;
        transitiveFiled = 10000;
    }

    @Override
    public String toString() {
        return "Person{" +
                "publicFiled=" + publicFiled +
                ", privateFiled=" + privateFiled +
                ", defaultFiled=" + defaultFiled +
                ", protectedFiled='" + protectedFiled + '\'' +
                ", transitiveFiled=" + transitiveFiled +
                ", staticFiled=" + staticFiled +
                '}';
    }
}
